#include "EventDispatcher.h"

namespace Fysics
{
	EventDispatcher::~EventDispatcher()
	{
	}

	void EventDispatcher::RegisterFunctionListener(EventType type, EventCallback callbackFn)
	{
		m_FunctionListenerMap[type].push_back(callbackFn);
	}

	void EventDispatcher::RegisterItemListener(EventType type, Item* item)
	{
		m_ItemListenerMap[type].push_back(item);
	}

	void EventDispatcher::RegisterTriggerEvent(EventType type, Item* trigger, EventCallback callbackFn)
	{
		m_TriggerEventMap[type].at(trigger).push_back(callbackFn);
	}

	void EventDispatcher::DispatchEvent(Event& event)
	{
		std::map<EventType, std::vector<EventCallback>>::iterator fn_it =
			m_FunctionListenerMap.find(event.GetType());
		if (fn_it != m_FunctionListenerMap.end())
		{
			std::vector<EventCallback>& callbackList = fn_it->second;
			for (EventCallback callback : callbackList)
			{
				callback(event);
			}
		}

		std::map<EventType, std::vector<Item*>>::iterator item_it =
			m_ItemListenerMap.find(event.GetType());
		if (item_it != m_ItemListenerMap.end())
		{
			std::vector<Item*>& itemList = item_it->second;
			for (Item* item : itemList)
			{
				item->OnEvent(event);
			}
		}
	}
}